<!--
 * @Author: 330GRX 617947173@qq.com
 * @Date: 2023-09-27 21:47:39
 * @LastEditors: 330GRX 617947173@qq.com
 * @LastEditTime: 2023-10-02 11:34:52
 * @FilePath: \Realtime-Chat\web\src\views\SetAvatar.vue
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
-->
<template>
  <div>
    <div class="container" v-if="isLoading">
      <img src="https://gifdb.com/images/high/rick-roll-loading-dance-aj78yi9h40c8kysk.webp" class="loader" alt="" />
      <span>加载太久了？<a href="/setAvatar">刷新</a></span>
    </div>
    <div class="container" v-else>
      <div class="title-container">
        <h1>请选择您的头像</h1>
      </div>
      <div class="avatars">
        <div v-for="(avatar, index) in avatars" :key="index" class="avatar" @click="setSelectedAvatar(index, $event)">
          <img :src="`data:image/svg+xml;base64,${avatar}`" alt="avatar" />
        </div>
      </div>
      <button class="submit-btn" @click="setProfilePicture">设置为头像</button>
      <span>没有喜欢的头像？<a href="/setAvatar">换一批</a></span>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { notification } from 'ant-design-vue'
import { setAvatarRoute } from '@/utils/APIRoutes'
import { ref, onMounted } from 'vue'
import { Buffer } from 'buffer'
import axios from 'axios'
// 路由实例对象
const router = useRouter()
// 头像生成api
const api = 'https://api.multiavatar.com/45678945'
// 头像数组
const avatars = ref([])
// 是否加载中
const isLoading = ref(true)
// 已选中头像的索引
const selectedAvatar = ref(null)

onMounted(async () => {
  // 如果没有登录 则跳转到登录页面
  if (!localStorage.getItem('chat-app-user')) {
    return router.push('/login')
  }

  // 获取头像
  const data = []
  for (let i = 0; i < 4; i++) {
    const image = await axios.get(`${api}/${Math.round(Math.random() * 1000)}`)
    const buffer = new Buffer(image.data)
    data.push(buffer.toString('base64'))
  }
  avatars.value = data
  isLoading.value = false
})

/**
 * @description:处理选中头像：1.记录下选中索引 2.显示选中样式
 * @param {*} index 选择头像的索引
 * @param {*} e 事件对象
 */
const setSelectedAvatar = (index, e) => {
  // 1.记录下选中索引
  selectedAvatar.value = index
  // 2.显示选中样式
  // 为数组转为真数组
  const avatarDoms = [...e.target.parentNode.parentNode.children]
  avatarDoms.forEach((item) => {
    item.className = 'avatar'
  })
  e.target.parentNode.classList.add('selected')
}
/**
 * @description: AntDesign的api，显示弹窗信息
 * @param {string} type 图标，可选值有success、info、warning、error
 * @param {string | VNode | () => VNode} message 通知提醒标题，必选
 */
const openNotificationWithIcon = (type, message) => {
  notification[type]({
    message,
    description: ''
  })
}
/**
 * @description: 处理点击设置为头像：1.校验 2.记录到本地存储（localhost） 3.发送ajax到后端
 */
const setProfilePicture = async () => {
  // 1.校验
  if (selectedAvatar.value === null) {
    openNotificationWithIcon('error', '请选择一个头像')
  } else {
    // 2.记录到本地存储（localhost）
    const user = await JSON.parse(localStorage.getItem('chat-app-user'))
    // 3.发送ajax到后端
    const { data } = await axios.post(`${setAvatarRoute}/${user._id}`, {
      image: avatars.value[selectedAvatar.value]
    })

    // 判断是否有头像，如有则跳转到chat页面
    if (data.isSet) {
      user.isAvatarImageSet = true
      user.avatarImage = data.image
      console.log(user)
      localStorage.setItem('chat-app-user', JSON.stringify(user))
      router.push('/')
    } else {
      openNotificationWithIcon('error', '头像设置失败，请再试一次')
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  gap: 3rem;
  background-color: #131324;
  height: 100vh;
  width: 100vw;
  .loader {
    max-inline-size: 100%;
  }
  .title-container {
    h1 {
      color: white;
    }
  }
  .avatars {
    display: flex;
    gap: 2rem;
    .avatar {
      border: 0.4rem solid transparent;
      padding: 0.4rem;
      border-radius: 5rem;
      display: flex;
      justify-content: center;
      align-items: center;
      transition: 0.5s ease-in-out;
      img {
        height: 6rem;
      }
    }
    .selected {
      border: 0.4rem solid rgb(100, 182, 135);
    }
  }
  .submit-btn {
    background-color: rgb(56, 72, 93);
    color: white;
    margin: 0 2rem;
    padding: 1rem 2rem;
    border: none;
    font-weight: bold;
    cursor: pointer;
    border-radius: 0.4rem;
    font-size: 1rem;
    transition: 0.5s ease-in-out;
    &:hover {
      background-color: rgb(100, 182, 135);
    }
  }
  span {
    color: white;
    text-transform: uppercase;
    text-align: center;
    a {
      color: rgb(100, 182, 135);
      text-decoration: none;
      font-weight: bold;
    }
  }
}
</style>
